// 设置 axios 请求的默认根路径
axios.defaults.baseURL = "https://hmajax.itheima.net";

// 封装显示 toast 提示
function showToast(message) {
  const toast = document.querySelector(".my-toast");
  toast.querySelector(".toast-body").innerText = message;
  new bootstrap.Toast(toast).show();
}

// 检查登录
function checkLogin() {
  if (!localStorage.getItem("mytoken")) {
    console.log("未登录，跳转到登录页面");
    location.href = "login.html";
  }
}

// 用户名渲染
function renderUsername() {
  const username = localStorage.getItem("myid");
  document.querySelector(".username").innerText = username;
}

// 退出登录
function logout() {
  localStorage.removeItem("mytoken");
  localStorage.removeItem("myid");
  location.href = "./login.html";
}

// 获取学生数据
async function getStudentData() {
  try {
    const res = await axios.get("/dashboard");
    renderStudentData(res.data.overview);
  } catch (error) {
    showToast("获取学生数据失败，请稍后再试");
    console.error("获取学生数据失败:", error);
  }
}

// 渲染学生数据
function renderStudentData(data) {
  Object.keys(data).forEach((key) => {
    document.querySelector(`.${key}`).innerHTML = data[key];
  });
}

// 获取 token
function getToken() {
  return localStorage.getItem("mytoken");
}

// 判断登录状态是否失效（通过token判断）
async function checkToken() {
  try {
    await axios.get("/dashboard", {
      headers: { Authorization: getToken() },
    });
  } catch (error) {
    if (error.response && error.response.status === 401) {
      showToast("登录状态失效，请重新登录");
      console.log("Token 失效，用户需要重新登录");
      logout();
    } else {
      showToast("请求失败，请稍后再试");
      console.error("请求失败:", error);
    }
  }
}

// 添加请求拦截器，用于在发送请求前进行一些处理
axios.interceptors.request.use(
  (config) => {
    const token = getToken();
    if (token) {
      config.headers.Authorization = token;
    }
    return config;
  },
  (error) => Promise.reject(error)
);

// 添加响应拦截器，用于在接收到响应后进行一些处理
axios.interceptors.response.use(
  (response) => response.data,
  (error) => Promise.reject(error)
);

// 渲染薪资走势
async function renderSalaryTrend() {
  const lineChart = echarts.init(document.querySelector("#line"));
  const salaryChart = echarts.init(document.querySelector("#salary"));
  const linesChart = echarts.init(document.querySelector("#lines"));

  // 获取薪资走势数据
  const salaryTrend = await axios.get("/dashboard");
  const { year, salaryData, groupData } = salaryTrend.data;
  // 控制台打印数据
  // console.log("总数据:", salaryTrend);
  console.log("分组数据:", groupData);
  groupData[1].map((item) => {
    console.log(item.name);
  });

  // 渲染薪资走势
  function renderSalaryTrendLineChart(year) {
    const option = {
      title: {
        text: "2025年薪资走势",
        left: 10,
        top: 15,
        textStyle: {
          fontSize: 16,
        },
      },
      legend: {
        data: ["薪资"],
        color: "#7ee47b",
        top: "3%",
      },
      xAxis: {
        type: "category",
        data: year.map((item) => item.month),
        axisLine: {
          show: true,
          lineStyle: {
            color: "#aeb1b5",
            type: "dashed",
          },
        },
        splitLine: {
          show: false,
        },
      },
      tooltip: {
        trigger: "axis",
        formatter: function (params) {
          return `${params[0].name} 薪资: ${params[0].value}`;
        },
        axisPointer: {
          type: "shadow",
        },
      },
      yAxis: {
        type: "value",
        axisLine: {
          show: false,
        },
        splitLine: {
          show: true,
          lineStyle: {
            type: "dashed",
            color: "#ccc",
            width: 1,
          },
        },
      },
      series: [
        {
          title: {
            textStyle: {
              fontSize: 16,
            },
          },
          name: "薪资",
          data: year.map((item) => item.salary),
          type: "line",
          smooth: true,
          symbolSize: 10,
          lineStyle: {
            width: 8,
            color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
              { offset: 0, color: "#d83fff" },
              { offset: 1, color: "#4A00E0" },
            ]),
          },
          areaStyle: {
            color: {
              type: "linear",
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                {
                  offset: 0,
                  color: "#2378f7",
                },
                {
                  offset: 1,
                  color: "rgba(255, 255, 255, 0)",
                },
              ],
              global: false,
            },
          },
        },
      ],
    };
    lineChart.setOption(option);
  }
  renderSalaryTrendLineChart(year);

  // 班级薪资分布图
  function renderSalaryTrendPieChart(salaryData) {
    const transformedData = salaryData.map((item) => {
      const totalCount = item.g_count + item.b_count;
      return { value: totalCount, name: item.label };
    });

    const option1 = {
      title: {
        text: "班级薪资分布",
        left: "10",
        top: "15",
      },
      tooltip: {
        trigger: "item",
      },
      legend: {
        bottom: "5%",
        left: "center",
      },
      series: [
        {
          name: "班级薪资分布",
          type: "pie",
          radius: ["50%", "70%"],
          center: ["50%", "45%"],
          avoidLabelOverlap: false,
          color: ["#ff9736", "#5495fd", "#39bcfa", "#2bd698"],
          itemStyle: {
            borderRadius: 10,
            borderColor: "#fff",
            borderWidth: 2,
          },
          label: {
            show: false,
            position: "center",
          },
          emphasis: {
            label: {
              show: false,
              fontSize: 40,
              fontWeight: "bold",
            },
          },
          labelLine: {
            show: false,
          },
          data: transformedData,
        },
      ],
    };
    salaryChart.setOption(option1);
  }
  renderSalaryTrendPieChart(salaryData);

  // 定义 option2 在函数外部
  let option2 = {
    grid: {
      left: 70,
      right: 80,
      top: 30,
      bottom: 30,
    },
    xAxis: {
      type: "category",
      data: [], // 初始为空，稍后填充
      axisLine: {
        lineStyle: {
          color: "#b7babe",
          type: "dashed",
        },
      },
    },
    yAxis: {
      type: "value",
      splitLine: {
        show: true,
        lineStyle: {
          color: ["#cfcfcf"],
          type: "dashed",
          with: "1",
        },
      },
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
    },
    series: [
      {
        name: "期望薪资",
        data: [],
        type: "bar",
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: "#2feba7" },
            { offset: 1, color: "rgba(255, 255, 255,1)" },
          ]),
        },
      },
      {
        name: "就业薪资",
        data: [],
        type: "bar",
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: "#5ca3ff" },
            { offset: 1, color: "rgba(255, 255, 255, 1)" },
          ]),
        },
      },
    ],
  };

  // 初始渲染
  if (groupData && groupData[1]) {
    option2.xAxis.data = groupData[1].map((item) => item.name);
    option2.series[0].data = groupData[1].map((item) => item.hope_salary);
    option2.series[1].data = groupData[1].map((item) => item.salary);
    linesChart.setOption(option2); // 渲染图表
  }

  // 点击按钮切换班级
  const btns = document.querySelector("#btns");
  btns.addEventListener("click", (e) => {
    // 判断类名为btn的按钮
    if (e.target.classList.contains("btn")) {
      // 清除类
      btns.querySelectorAll(".btn").forEach((btn) => {
        btn.classList.remove("btn-blue");
      });
      // 添加btn-blue类
      e.target.classList.add("btn-blue");

      // 根据点击的按钮渲染对应页数的数据
      const group = e.target.innerText;
      console.log(group);

      // 确保 groupData[group] 存在
      if (groupData[group]) {
        option2.xAxis.data = groupData[group].map((item) => item.name);
        option2.series[0].data = groupData[group].map(
          (item) => item.hope_salary
        );
        option2.series[1].data = groupData[group].map((item) => item.salary);

        // 更新图表
        linesChart.setOption(option2);
      } else {
        console.error("未找到对应的分组数据:", group);
      }
    }
  });
}
